<%@ page import="java.util.List" %>
<%@ page import="com.example.demo_text.CourseDAO" %>
<%@ page import="com.example.demo_text.EnrollmentDAO" %>
<%@ page import="com.example.demo_text.StudentEnrollment" %>
<%@ page import="com.example.demo_text.UserDAO" %>
<%@ page import="user.User" %>
<%@ page import="com.example.demo_text.Course" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
  String userIdStr = request.getParameter("userId");
  int userId = Integer.parseInt(userIdStr);

  User user = UserDAO.getUserById(userId);
  List<Course> allCourses = CourseDAO.getAllCourses();
  List<StudentEnrollment> enrolledCourses = EnrollmentDAO.getEnrollmentsByUserId(userId);
%>

<html>
<head>
  <title>编辑 <%= user.getUsername() %> 的选课</title>
  <style>
    /* 使用与 manageCourse.jsp 相同的样式 */
  </style>
</head>
<body>

<div class="card">
  <h2>📚 编辑 <%= user.getUsername() %> 的选课信息</h2>
  <p>请选择该学生要选修的课程：</p>

  <form action="UpdateAllEnrollmentsServlet" method="post">
    <input type="hidden" name="userId" value="<%= userId %>" />

    <% for (Course course : allCourses) { %>
    <div style="margin: 10px 0;">
      <label>
        <input type="checkbox"
               name="courseId"
               value="<%= course.getId() %>"
                <% if (enrolledCourses.stream().anyMatch(e -> e.getCourseId() == course.getId())) { %> checked <% } %>
        />
        <%= course.getName() %>
      </label>
    </div>
    <% } %>

    <br/>
    <button type="submit">保存选课</button>
  </form>

  <a href="manageCourse.jsp" class="back-link">返回选课管理</a>
</div>

</body>
</html>
